package com.example.wblog.service;

import com.example.wblog.dao.LoginTicketDAO;
import com.example.wblog.dao.UserDAO;
import com.example.wblog.model.LoginTicket;
import com.example.wblog.model.User;
import com.example.wblog.util.CookieUtil;
import com.example.wblog.util.MD5Util;
import com.example.wblog.util.MD5Util;
import com.example.wblog.util.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private LoginTicketDAO loginTicketDAO;

    @Autowired
    private UserDAO userDAO;

    public Map<String, String> login(String name, String password) {
        Map<String, String> map = new HashMap<>();
        //check name
        User user = userDAO.selectByName(name);
        if (user == null) {
            map.put("msg", "no user");
            return map;
        }
        if (!user.getPassword().equals(MD5Util.next(password + user.getSalt()))) {
            map.put("msg", "wrong password");
            return map;
        }
        map.put("ticket", getTicket(user.getId()));
        return map;
    }


    public void logout(HttpServletRequest request, HttpServletResponse response, String ticket) {
        loginTicketDAO.deleteByTicket(ticket);
        CookieUtil.removeCookie("ticket", request, response);
    }


    private String getTicket(int userId) {
        final long EXPIRED_TIME = 1000 * 3600 * 24;
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setStatus(0);
        loginTicket.setUserId(userId);
        loginTicket.setTicket(UUIDUtil.next());
        Date date = new Date();
        date.setTime(date.getTime() + EXPIRED_TIME);
        loginTicket.setExpired(date);

        loginTicketDAO.add(loginTicket);

        return loginTicket.getTicket();
    }
}
